<template>
    <div class="message" v-scroll-bottom="session.messages">
        <ul v-if="session">
            <li v-for="item in session.messages">
                <p class="time">
                    <span>{{ item.date | time }}</span>
                </p>
                <el-row class="main" :class="{ self: item.self }">
                    <el-col :span="2">
                        <el-avatar size="small" :src="item.self ? user.img : session.user.img"></el-avatar>
                    </el-col>
                    <el-col :span="20">
                        <div class="text">{{ item.msg }}</div>
                    </el-col>
                </el-row>
            </li>
        </ul>
    </div>
</template>

<script>
import { mapState } from 'vuex';
export default {
    computed: {
        ...mapState({
            user: (state) => state.userInfo,
            session: ({ chat: { sessions, currentSessionId } }) =>{
                const session = sessions.find((session) => session.user.userId === currentSessionId)
                return session ? session : {}
            },
        }),
    },
    filters: {
        // 将日期过滤为 hour:minutes
        time(date) {
            if (typeof date === 'string') {
                date = new Date(date);
            }
            return date.getHours() + ':' + date.getMinutes();
        },
    },
    directives: {
        // 发送消息后滚动到底部
        'scroll-bottom': {
            inserted(el) {
                el.scrollTop = el.scrollHeight - el.clientHeight;
            },
        },
    },
};
</script>

<style lang="less" scoped>
.message {
    padding: 10px 15px;
    overflow-y: scroll;

    li {
        margin-bottom: 15px;
    }
    .time {
        margin: 7px 0;
        text-align: center;

        > span {
            display: inline-block;
            padding: 0 18px;
            font-size: 12px;
            color: #fff;
            border-radius: 2px;
            background-color: #dcdcdc;
        }
    }
    .text {
        display: inline-block;
        position: relative;
        padding: 0 10px;
        max-width: ~'calc(100% - 40px)';
        min-height: 30px;
        line-height: 2.5;
        font-size: 12px;
        text-align: left;
        word-break: break-all;
        background-color: #fafafa;
        border-radius: 4px;

        &:before {
            content: ' ';
            position: absolute;
            top: 9px;
            right: 100%;
            border: 6px solid transparent;
            border-right-color: #fafafa;
        }
    }

    .self {
        text-align: right;
        .el-col{
            float: right;
        }

        .text {
            background-color: #b2e281;

            &:before {
                right: inherit;
                left: 100%;
                border-right-color: transparent;
                border-left-color: #b2e281;
            }
        }
    }
}
</style>